package ExceptionHelper

import (
	"gitee.com/tym_hmm/hlog"
)

type Exception struct {
	Code    int
	Message string
}

type ExceptionHandler func(Exception)

type ExceptionStruct struct {
	catch   ExceptionHandler
	finally func()
	try     func()
}

// 抛异常
func ThrowLog(code int, message string, param ...interface{}) {
	throwException(code, message, true, param)
}

func Throw(code int, message string, param ...interface{}) {
	throwException(code, message, false, param)
}

func throwException(code int, message string, isLog bool, param ...interface{}) {
	if param != nil && isLog {
		hlog.NewStdLog().Error("code:%d,\nmessage: %s,\nerr:%v", code, message, param)
	}
	panic(Exception{Code: code, Message: message})
}

// 尝试
func Try(handler func()) *ExceptionStruct {
	return &ExceptionStruct{
		try: handler,
	}
}

// 捕获异常方法设置
func (ex *ExceptionStruct) Catch(catch func(Exception)) *ExceptionStruct {
	ex.catch = catch
	return ex
}

// 最终都要执行的方法
func (ex *ExceptionStruct) Finally(finally func()) *ExceptionStruct {
	ex.finally = finally
	return ex
}

// 这里总体执行
func (ex *ExceptionStruct) Exc() {
	defer func() {
		if e := recover(); nil != e {
			//	if isLog {
			//hlog.NewStdLog().Error("err=>%+v", e)

			exception := e.(Exception)
			catch := ex.catch
			if catch != nil {
				catch(exception)
			}
		}
		finally := ex.finally
		if finally != nil {
			finally()
		}
	}()
	ex.try()
}
